package com.zlsy.thread.objectandthreadcommonsuse;

/**
 * @author zhouliang
 * @date 2020/03/05
 **/
public class WaitNotifyAll implements Runnable {

    private final static Object instance = new Object();

    @Override
    public void run() {
        synchronized (instance) {
            System.out.println(Thread.currentThread().getName() + " got instance lock。");
            try {
                System.out.println(Thread.currentThread().getName() + " wait to start.");
                instance.wait();
                System.out.println(Thread.currentThread().getName() + "'s wait to end.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WaitNotifyAll waitNotifyAll = new WaitNotifyAll();
        Thread thread = new Thread(waitNotifyAll);
        Thread thread1 = new Thread(waitNotifyAll);
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (instance){
                    instance.notifyAll();
                    System.out.println("thred2 NOTIFY.");
                }
            }
        });
        thread.start();
        thread1.start();
        Thread.sleep(200);
        thread2.start();
    }
}
